<route lang="json5" type="page">
{
	style: {
		navigationStyle: 'custom',
		navigationBarTitleText: '倍阅书目',
	},
}
</route>

<template>
	<view class="page-bookrack">
		<fly-navbar backgroundColor="#ffffff" leftText="倍阅书目" fixed />
		<view class="w-full box-border">
			<view class="w-full h-[110rpx] pb-[13rpx] px-4 flex items-end box-border">
				<view
					class="w-full flex items-center justify-between h-[63rpx] rounded-[30rpx] pl-[37rpx] pr-[22rpx] box-border"
					style="background: #f3f3f5"
				>
					<view class="flex-1 h-full box-border pr-4">
						<input
							@input="input"
							:value="search_context"
							placeholder="请输入书名、作者"
							class="h-full py-[15rpx] text-[#303030] text-[30rpx] box-border"
							type="text"
						/>
					</view>
					<image :src="baseImg + '/book/book-search.png'" class="w-[30rpx] h-[30rpx]"></image>
				</view>
			</view>
			<view class="w-full flex flex-col px-4 box-border" v-if="!isSearch">
				<view
					class="h-[63rpx] w-fit mt-[22rpx] text-[#ABABAB] text-[26rpx] px-3 rounded-[30rpx] inline-flex justify-center items-center"
					style="background: #f3f3f5"
					v-for="item in history"
					:key="item"
					@tap="toSearch(item)"
				>
					{{ item }}
				</view>
				<view
					v-if="history.length"
					class="h-[63rpx] w-fit mt-[39rpx] text-[#ABABAB] text-[26rpx] px-3 rounded-[30rpx] inline-flex justify-center items-center"
					style="background: #f3f3f5"
					@tap="clearHistory"
				>
					<image
						:src="baseImg + '/book/book-clear.png'"
						class="w-[30rpx] h-[30rpx] mr-[13rpx]"
					></image
					>清空记录
				</view>
			</view>
			<scroll-view
				class="w-full"
				:style="{ height: contentHeight - 110 + 'rpx' }"
				scroll-y
				v-if="thisPage === 1 && bookList.length && isSearch"
				@scrolltolower="scrolltolower"
			>
				<view class="w-full px-4 py-4 box-border">
					<view class="w-full box-border rounded-[30rpx] recommend-box">
						<view
							v-if="search_context && count"
							class="text-[#303030] text-[33rpx] px-4 pt-4 box-border font-bold"
						>
							{{ count }}条搜索结果
						</view>
						<view
							v-for="item in bookList"
							:key="item.id"
							@tap="toBook(item.id)"
							class="mb-4 last:mb-0"
						>
							<book-item :item="item" @receive="receive"></book-item>
						</view>
					</view>
				</view>
			</scroll-view>
			<no-page
				v-if="thisPage === 0 || (thisPage === 1 && !bookList.length)"
				height="100%"
				:type="thisPage === 0 ? 'btn' : 'msg'"
				:title="title"
				@click="retry"
			></no-page>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { storeToRefs } from 'pinia';
import { useUserStore } from '@/store';
import { getRecommendBookList } from '@/service/book';
import { systemInfo } from '@/utils/getSystemInfo';
import { getReceivePoint } from '@/service/user';
import { debounce } from '@/utils';
import { toAuthPage } from '@/utils/jump';
import onShare from '@/hooks/useShare';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { onShareAppMessage, onShareTimeline } = onShare();

const { contentHeight } = systemInfo();
const baseImg = ref(import.meta.env.VITE_STATIC_IMAGE);
const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);
const bookList = ref([]);
const title = ref('');
const thisPage = ref(-1);
const page = ref({ number: 1, size: 10 });
const hasMore = ref(true);
const search_context = ref('');
const isSearch = ref(false);
const history = ref([]);
const count = ref(0);

onLoad(() => {
	if (!uni.getStorageSync('bookHistoryList')?.length) {
		getList();
	}
});

onShow(() => {
	history.value = uni.getStorageSync('bookHistoryList') || [];
	// search_context.value = '';
	// if (isSearch.value) {
	// 	page.value.number = 1;
	// 	getList();
	// }
});

const input = debounce(e => {
	search_context.value = e.detail.value;
	getList();
}, 500);

const toBook = (id: number) => {
	if (id === undefined) return;
	if (!userInfo.value.student_id) {
		toAuthPage({}, { type: 'navigateTo', url: `/pages-book/details/index?id=${id}` });
	} else {
		uni.navigateTo({
			url: `/pages-book/details/index?id=${id}`,
		});
	}
};

const toSearch = (name: string) => {
	search_context.value = name;
	page.value.number = 1;
	getList();
};

const clearHistory = () => {
	search_context.value = '';
	page.value.number = 1;
	if (uni.getStorageSync('bookHistoryList')) {
		uni.removeStorageSync('bookHistoryList');
	}
	getList();
};

const scrolltolower = () => {
	if (!hasMore.value) return;
	page.value.number++;
	getList();
};

const getList = async () => {
	uni.showLoading({ title: '加载中...' });
	try {
		const res = await getRecommendBookList({
			page: page.value.number,
			page_size: page.value.size,
			search_context: search_context.value,
			student_id: userInfo.value.student_id,
		});
		uni.hideLoading();
		if (res.status_code === 200 && res.data) {
			thisPage.value = 1;
			count.value = res.data.count;
			bookList.value =
				page.value.number === 1 ? res.data.book_list : [...bookList.value, ...res.data.book_list];
			if (res.data.book_list.length < page.value.size) {
				hasMore.value = false;
			}
			if (!bookList.value.length) {
				title.value = '暂无数据';
				isSearch.value = false;
			} else {
				isSearch.value = true;
				const arr = uni.getStorageSync('bookHistoryList') || [];
				if (!arr.includes(search_context.value.trim()) && search_context.value) {
					if (arr.length >= 10) {
						arr.shift();
					}
					arr.push(search_context.value);
					uni.setStorageSync('bookHistoryList', arr);
				}
			}
		} else {
			thisPage.value = 0;
			title.value = res.message;
		}
	} catch (error) {
		uni.hideLoading();
		thisPage.value = 0;
		title.value = '服务器异常';
	}
};

const retry = () => {
	hasMore.value = true;
	page.value = { number: 1, size: 10 };
	getList();
};

const receive = async item => {
	uni.showLoading({
		title: '领取中...',
	});
	try {
		const res = await getReceivePoint({
			student_id: userInfo.value.student_id,
			book_id: item.id,
		});
		uni.hideLoading();
		if (res.status_code === 200) {
			uni.showToast({
				icon: 'none',
				title: '领取成功',
				success: () => {
					retry();
				},
			});
		} else {
			uni.showToast({
				icon: 'none',
				title: res.message,
			});
		}
	} catch (error) {
		uni.hideLoading();
		uni.showToast({
			icon: 'none',
			title: '领取失败,请重试',
		});
	}
};
</script>

<style lang="scss">
page {
	background: #fff;
}
</style>
<style lang="scss" scoped>
.page-bookrack {
	width: 100%;
	height: 100vh;
	background: #fff;
}

.destroy::after {
	display: inline-flex;
	align-items: center;
	justify-content: center;
	width: 75rpx;
	height: 55rpx;
	color: #919191;
	content: 'x';
	background: #e8e8e8;
	border-radius: 27rpx 0 0 27rpx;
}

.recommend-box {
	box-shadow:
		3rpx 3rpx 4rpx 3rpx rgb(0 0 0 / 2%),
		3rpx 5rpx 45rpx 3rpx rgb(0 0 0 / 10%);
}

.triangle {
	width: 0;
	height: 0;
	margin-left: 11rpx;
	border-top: 15rpx solid #777;
	border-right: 10rpx solid transparent;
	border-left: 10rpx solid transparent;
}
</style>
